package main

import (
	"fmt"
	"log"
	"net/http"
	"time"
)

func sseHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
		return
	}

	ctx := r.Context()

	for {
		select {
		case <-time.After(1 * time.Second):
			fmt.Fprintf(w, "{\"time\":\"%v\"}", time.Now().Unix())
			flusher.Flush()
		case <-ctx.Done():
			log.Println("Client closed connection")
			return
		}
	}
}

func main() {
	http.HandleFunc("/events", sseHandler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}
